package ru.st.selenium;

import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;

import org.testng.*;
import org.testng.annotations.*;

import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;

import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;

public class SearchFilm extends ru.st.selenium.pages.TestBase {
  private boolean acceptNextAlert = true;
  private StringBuffer verificationErrors = new StringBuffer();

  @BeforeClass
  public void Login () throws Exception {
		// LOGIN (login code is placed here just for testing purposes of this class)
	    driver.get(baseUrl + "/php4dvd/");
	    driver.findElement(By.id("username")).clear();
	    driver.findElement(By.id("username")).sendKeys("admin");
	    driver.findElement(By.name("password")).clear();
	    driver.findElement(By.name("password")).sendKeys("admin");
	    driver.findElement(By.name("submit")).click();
	    for (int second = 0;; second++) {
	    	if (second >= 60) fail("timeout");
	    	try { if (isElementPresent(By.id("results"))) break; } catch (Exception e) {}
	    	Thread.sleep(1000);
	    }	  	  
  }
  
  @Test
  public void testSearchExistingFilm() throws Exception {
	  
	// 1. SEARCH FOR EXISTING 'APOCALYPSE' FILM (POSITIVE TEST)  
    driver.get(baseUrl + "/php4dvd/");
    
    // name of existing film to search
    String searchedFilm = "Apocalypse";
    
    // locate search input field
    WebElement searchInput = driver.findElement(By.id("q"));
    
    // type searched film name
    searchInput.clear();
    searchInput.sendKeys(searchedFilm);
    
    // initiate search and wait for results 
    searchInput.sendKeys(Keys.RETURN);
    
    for (int second = 0;; second++) {
    	if (second >= 60) fail("timeout");
    	try { if (isElementPresent(By.id("results"))) break; } catch (Exception e) {}
    	Thread.sleep(1000);
    }

	// verify that existing film was found in search results (there can be several films found)
	WebElement found_film = driver.findElement(By.xpath(".//*/div[@id='results']//div[contains(text(), "+searchedFilm+")]"));
	String text = found_film.getText();
	assertTrue(Pattern.compile(".*"+searchedFilm+".*").matcher(text).find());
  }

  @Test
  public void testSearchNonExistingFilm() throws Exception {

	  // 2. SEARCH FOR NON EXISTENT 'LOST MOVIE' FILM (NEGATIVE TEST)
	    driver.get(baseUrl + "/php4dvd/");

	    // name of existing film to search
	    String invalidFilm = "Lost Movie";
	    
	    // locate search input field    
	    WebElement searchInput = driver.findElement(By.id("q"));
	    
	    // type searched film name (film does not exist in database)
	    searchInput.clear();
	    searchInput.sendKeys(invalidFilm);
	    
	    // initiate search and wait for results
	    searchInput.sendKeys(Keys.RETURN);
	    
	    for (int second = 0;; second++) {
	    	if (second >= 60) fail("timeout");
	    	try { if (isElementPresent(By.id("results"))) break; } catch (Exception e) {}
	    	Thread.sleep(1000);
	    }

	    // verify that valid message appears in case movie was not found
	    assertEquals("No movies where found.", driver.findElement(By.id("results")).getText());
	    
	    // verify that non existing film is not present in search results
	    assertThat(invalidFilm, is(not(driver.findElement(By.id("results")).getText())));    
  }
  
  private boolean isElementPresent(By by) {
    try {
      driver.findElement(by);
      return true;
    } catch (NoSuchElementException e) {
      return false;
    }
  }

  private String closeAlertAndGetItsText() {
    try {
      Alert alert = driver.switchTo().alert();
      String alertText = alert.getText();
      if (acceptNextAlert) {
        alert.accept();
      } else {
        alert.dismiss();
      }
      return alertText;
    } finally {
      acceptNextAlert = true;
    }
  }
}
